#!/usr/bin/env python
# -*- coding: utf-8 -*-

import wx                        # This module uses the new wx namespace
import sys
import os
import platform
import locale
import splash_screen
import version_info

# import images                  # For PyEmbeddedImage

getTextType = "wx"               # Using wxPython's GetTranslation

_ = wx.GetTranslation            # Define _ or add _ to builtins in your app file

print ''
print 'Folders :'

appDir = os.path.split(os.path.abspath(sys.argv[0]))[0]
print 'Path "app" folder : %s' % (appDir)

icons_Location = os.path.join(appDir, "icons")
print 'Path "icons" folder : %s' % (icons_Location)

images_Location = os.path.join(appDir, "bitmaps")
print 'Path "images" folder : %s' % (images_Location)

lang_Location = os.path.join(appDir, "locale")
print 'Path "locale" folder : %s' % (lang_Location)

music_Location = os.path.join(appDir, "music")
print 'Path "music" folder : %s' % (music_Location)

license_Location = os.path.join(appDir, "license")
print 'Path "license" folder : %s' % (license_Location)

config_Location = os.path.join(appDir, "config")
print 'Path "config" folder : %s' % (config_Location)

print ''
print 'Files :'

path = os.path.abspath(sys.argv[0])
print 'Path "python" file : %s' % (path)

configLang_File = os.path.join(config_Location, "Config.cfg")
print 'Path "config lang" file : %s' % (configLang_File)

configSource_File = os.path.join(config_Location, "Source.cfg")
print 'Path "config source" file : %s' % (configSource_File)

#----------------------------------------------------------------------

class PyarchiverApp(wx.App):
    def OnInit(self):
        wx.InitAllImageHandlers()
        self.SetAppName(u"myapp")  # Used to identify app in $HOME/
        
        # Simplified init method 
        self.init_i18n()   # Internationalization (i18n)
        self.do_config()   # Language configuration

        self.set_lang(self.config.Read("Language"))
    
        # Check runtime version
        if version_info.WXPYTHONVERSION_STRING != wx.VERSION_STRING:
            wx.MessageBox(caption=_("Warning"),
                          message=_("You're using version %s of wxPython, but \nthis app was written for version %s.\nThere may be some version incompatibilities...")
                          % (wx.VERSION_STRING, version_info.WXPYTHONVERSION_STRING))

        # Create and show the splash screen.  It will then create 
        # and show the main frame when it is time to do so
        wx.SystemOptions.SetOptionInt("mac.window-plain-transition", 1)

        bitmapDir = os.path.join(appDir, "bitmaps")
        bmp = wx.Bitmap(os.path.join(bitmapDir, "splashScreen.png"))        
        # or PyEmbeddedImage
        # bmp = images.splash_screen.GetBitmap()
        self.splash = splash_screen.My_SplashScreenCustom(None, bitmap=bmp)
        self.splash.Show()
        print ""
        print "Display the splashScreen"
            
        return True
    
    #-----------------------------------------------------------------------

    def init_i18n(self):
        # Set locale for wxWidgets
        # usually you would define wx.Locale in your wx.App.OnInit class.
        # for the demo we just define it in this module
        self.locale = None
        # wx.Locale.AddCatalogLookupPathPrefix(opj('data/locale'))
        wx.Locale.AddCatalogLookupPathPrefix("locale")
        self.update_language(wx.LANGUAGE_DEFAULT)


    def update_language(self, lang):
        # Make *sure* any existing locale is deleted before the new
        # one is created.  The old C++ object needs to be deleted
        # before the new one is created, and if we just assign a new
        # instance to the old Python variable, the old C++ locale will
        # not be destroyed soon enough, likely causing a crash.
        if self.locale:
            assert sys.getrefcount(self.locale) <= 2
            del self.locale
        
        # create a locale object for this language
        self.locale = wx.Locale(lang)
        if self.locale.IsOk():
            self.locale.AddCatalog("myapp")
        else:
            self.locale = None
            
    #-----------------------------------------------------------------------
        
    def do_config(self):
        """
        Do configuration stuff here (either registery or file)
        ApplicationName: application name
        VendorName: author or company
        Language: en (default)
        Keys: (e.g.)
        ProgramLocation: cwd
        ConfigLocation: path\Config\Config.cfg
        ApplicationVersion : application version
        
        """

        appVersion = "%s" % version_info.APPLICATIONVERSION_STRING
        configDir = os.path.join(appDir, "config")
        configFile = os.path.join(configDir, "Config.cfg")
        # progLoc = os.getcwd()
        # configFile = os.path.join(progLoc, "Config\Config.cfg")
        
        self.config = wx.FileConfig(appName="PyArchiver",
                                    vendorName="Pascal Fautrero and JCharles",
                                    localFilename=configFile,
                                    style=wx.CONFIG_USE_LOCAL_FILE)

        if not self.config.HasEntry("ProgramLocation"):
            self.config.Write(key="ProgramLocation", value=progLoc)
        if not self.config.HasEntry("ConfigLocation"):
            self.config.Write(key="ConfigLocation", value=configFile)
        if not self.config.HasEntry("ApplicationVersion"):
            self.config.Write(key="ApplicationVersion", value=appVersion)
        if not self.config.HasEntry("ApplicationName"):
            self.config.Write(key="ApplicationName", value="PyArchiver")
        if not self.config.HasEntry("VendorName"):
            self.config.Write(key="VendorName", value="Pascal | JCharles")
        if not self.config.HasEntry("Language"):
            self.config.Write(key="Language", value="fr")


    def set_lang(self, lang):
        if getTextType == "wx":
            self.set_lang_wx(lang)
        elif getTextType == "py":
            self.set_lang_py(lang)

            
    def set_lang_py(self, lang):
        if lang in ["fr"]:
            langFr = gettext.translation("myapp", localeDir, languages=["fr"])
            langFr.install()

        if platform.system() == "Linux":
            try:
                # To get some language settings to display properly
                os.environ["LANGUAGE"] = "fr"

            except (ValueError, KeyError):
                pass

        else:
            langEn = gettext.translation("myapp", localeDir, languages=["en"])
            langEn.install()
        
        if platform.system() == "Linux":
            try:
                # To get some language settings to display properly
                os.environ["LANGUAGE"] = "en"

            except (ValueError, KeyError):
                pass
            
        
    def set_lang_wx(self, lang):
        if lang in ["fr"]:
            if hasattr(self, "locale"):
                del self.locale
            self.locale = wx.Locale(wx.LANGUAGE_FRENCH, 
                        wx.LOCALE_LOAD_DEFAULT)
            self.locale.AddCatalog("myapp")
            self.config.Write(key="Language", value="fr")

            if platform.system() == "Linux":
                os.environ["LANGUAGE"] = "fr"

                
        else:
            if hasattr(self, "locale"):
                del self.locale
            self.locale = wx.Locale(wx.LANGUAGE_ENGLISH, 
                        wx.LOCALE_LOAD_DEFAULT)
            self.locale.AddCatalog("myapp")
            self.config.Write(key="Language", value="en")

            if platform.system() == "Linux":
                os.environ["LANGUAGE"] = "en"
